package com.example.jbservice.handler;

import com.example.jbservice.Constant.MessageConstant;
import com.example.jbservice.Exception.BaseException;
import com.example.jbservice.Result.Result;
import com.mysql.cj.jdbc.exceptions.CommunicationsException;
import com.mysql.cj.jdbc.exceptions.MysqlDataTruncation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.websocket.SessionException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.sql.SQLTransientConnectionException;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex){
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }
        /**
         * 捕获业务异常
         * @param
         * @return
         */
      /*  @ExceptionHandler
     public  Result    exceptionHandler(SQLIntegrityConstraintViolationException ex){
         String message=ex.getMessage();
         if(message.contains("Duplicate entry")){
             String[] split=message.split(" ");
             String username=split[2];
             String msg=username+ MessageConstant.ALREADY_EXISTS;
             return  Result.error(msg);
         }
         else {

             return  Result.error(MessageConstant.UNKNOWN_ERROR);
         }
     }*/

    @ExceptionHandler(value = Exception.class)
    public Result handle(Exception ex) {
        log.error("已捕捉到异常！"+ex);

        String errmsg="";

         if (ex instanceof MysqlDataTruncation) {
             errmsg="字段数据长度超过限制！";
        }else if (ex instanceof SQLIntegrityConstraintViolationException) {
             String[] split=ex.getMessage().split(" ");
             String username=split[2];
             errmsg=username+ MessageConstant.ALREADY_EXISTS;
             //errmsg=
        }else {
             errmsg=ex.getMessage();
        }

        return  Result.error (errmsg);
    }
}
